package org.nhindirect.stagent;

public class CharReader 
{
    String m_source;
    int m_position;
    int m_maxPosition;
    
    public CharReader(StringSegment source)
    {
        this.m_source = source.getSource();
        this.m_position = source.getStartIndex();
        this.m_maxPosition = this.m_position + source.getLength();
    }

    public CharReader(String source)
    {
        if (source == null || source.length() == 0)
        {
            throw new IllegalArgumentException();
        }

        this.m_source = source;
        this.m_position = 0;
        this.m_maxPosition = this.m_position + source.length();
    }
    
    public String getSource()
    {
        return this.m_source;
    }

    public int getPosition()
    {
        return this.m_position - 1;
    }
    
    public boolean isDone()
    {
        return (this.m_position == this.m_maxPosition);
    }
    
    public char read()
    {
        if (this.isDone())
        {
            return Character.MIN_VALUE;
        }

        return this.m_source.charAt(this.m_position++);
    }
    
    public boolean readTo(char chTo)
    {
        char ch;
        while ((ch = this.read()) != Character.MIN_VALUE)
        {
            if (ch == chTo)
            {
                return true;
            }
        }
        
        return false;
    }
    
    public char peek()
    {
        int next = this.m_position + 1;
        if (next >= this.m_maxPosition)
        {
            return Character.MIN_VALUE;
        }
        
        return this.m_source.charAt(next);
    }
    
    public boolean isNext(char ch)
    {
        return (this.peek() == ch);
    }
    
    public char peekPrev()
    {
        int prev = this.m_position - 1;
        if (prev < 0)
        {
            return Character.MIN_VALUE;
        }
        
        return this.m_source.charAt(prev);
    }
    
    public boolean isPrev(char ch)
    {
        return (this.peekPrev() == ch);
    }
}
